4/* 
* @author: José Marques <jlmarques@tap.pt>
*/


/**
* Detects IE < 9
*/

var isIE = !$.support.leadingWhitespace;


$.fn.mColorPicker.init.allowTransparency = false;
$.fn.mColorPicker.init.showLogo = false;



$(document).ready(function() {


    /**
    * Change List style	 
    */

    $("#listButtons li a").live("click", function() {
        itemListChanger($(this).attr("class"));
    });

    //itemShowHideDetail();


    /**
    * Set the user view 
    */

    if ($.cookie("listView") != null) {
        itemListChanger($.cookie("listView"))
    }
    else {
        itemListChanger("bigIcons")
    }

    /**
    * Allow the user to sort the icon list	 
    */

    $("#itemList").sortable({
        cursor: "crosshair",
        opacity: 0.5,
        handle: "a.move",
        update: function(event, ui) { updateListPositions(this); }
    });
    $("#itemList").disableSelection();

    /**
    * Delete an item from the list
    */

    $("#itemList * a.delete").live("click", function() {

        var item = $(this)

        $("#dialog-confirm").dialog({
            resizable: false,
            height: 140,
            modal: true,
            buttons: {
                "Eliminar": function() {
                    deleteListItem(item);
                },
                Cancel: function() {
                    $(this).dialog("close");
                    return false;
                }
            }
        });
        return false;
    });

    $(".confirmDelete").live("click", function() {

        var item = $(this)

        $("#dialog-confirm").dialog({
            resizable: false,
            height: 140,
            modal: true,
            buttons: {
                "Eliminar": function() {
                    deleteListItem(item);
                },
                Cancel: function() {
                    $(this).dialog("close");
                    return false;
                }
            }
        });
        return false;
    });


    /**
    * Edit an item
    */

    $("#itemList * a.edit").live("click", function() {

        var editUrl = $(this).text();
        //window.location = "form.aspx";
        window.location = "AdminItem.aspx?Id="+editUrl;

    });

    /**  
    * Get item detail page  
    */

    $("#itemList * span.info").live("click", function() {

        //get the item id  
        var itemId = $(this).parent().parent().parent().attr("id");

        window.location = "detail.html?itemId=" + itemId;

    });

    /**
    * Slide and show/hide top tabs 
    */

    $("header nav ul li").hover(
	function() {
	    $(this).animate({ "width": "140" }, "swing");

	},
	function() {
	    $(this).animate({ "width": "45" }, "swing");

	});

    /**
    * Activate the search engine drop down
    */

    $("#searchEngine").click(function() {
        if (!$("#searchEngineOptions").hasClass("active")) {
            $("#searchEngineOptions").slideDown();
            $("#searchEngineOptions").addClass("active");

            //fix for IE 7 - messes with z-index
            if ($.support.boxModel) {
                $("#page").css('z-index', 88);
                $("#search").css('z-index', 99);
            }

        }

        else {
            $("#searchEngineOptions").slideUp();
            $("#searchEngineOptions").removeClass();
        }
    });




    /**
    * Select the search engine
    */

    var searchEngine = "";

    $("#searchEngineOptions li").click(function() {

        changeSearchEngine($(this));
    });


    /**
    * Submit Search Query
    */

    $("#searchButton").click(function() {

        var currentSearchQuery = $("#searchBox").val();

        if (searchEngineURL.indexOf("http") != -1) {
            window.open(searchEngineURL + currentSearchQuery, "SearchWindow");
        }
        else {
            document.location = searchEngineURL + currentSearchQuery;
        }
    });

    /****************************************************************************************
    * FORM
    *****************************************************************************************/

    /**
    * Show/hide advanced options panel
    */

    var advancedOptions;

    $(".advancedOptions h4").live("click", function() {

        advancedOptions = $(this).parent();

        if ($(advancedOptions).hasClass("closed")) {
            $(this).next().show();
            $(advancedOptions).removeClass("closed");
            $(advancedOptions).addClass("open");
        }

        else {
            $(this).next().hide();
            $(advancedOptions).removeClass("open");
            $(advancedOptions).addClass("closed");
        }

    });

    var advancedUserOptions;

    $(".advancedUserOptions h4").live("click", function() {

    advancedUserOptions = $(this).parent();

    if ($(advancedUserOptions).hasClass("closed")) {
            $(this).next().show();
            $(advancedUserOptions).removeClass("closed");
            $(advancedUserOptions).addClass("open");
        }

        else {
            $(this).next().hide();
            $(advancedUserOptions).removeClass("open");
            $(advancedUserOptions).addClass("closed");
        }

    });

    var advancedBackListOptions;

    $(".advancedBackListOptions h4").live("click", function() {

    advancedBackListOptions = $(this).parent();

    if ($(advancedBackListOptions).hasClass("closed")) {
            $(this).next().show();
            $(advancedBackListOptions).removeClass("closed");
            $(advancedBackListOptions).addClass("open");
        }

        else {
            $(this).next().hide();
            $(advancedBackListOptions).removeClass("open");
            $(advancedBackListOptions).addClass("closed");
        }

    });
    /**
    * Remove a tag
    */

    //activateRemoveTags();

    /**
    * Handles the tags input
    */

    handleTagEdit();


    $("#submitForm").click(function() {

        $("#submitForm").submit();
        showProgress();

    });

    //adds padding to list elements at the edges
    // IE only
    resetListPositions();


    /**
    * Activate the color picker
    */

    var originalBackgroundColor = $('body').css('background');
    $('.backgroundColor').bind('colorpicked', function() {


        $('body').css('background', $(this).val());
        // savePerferedColor($(this).val());

    });



    /**
    * Personalization menu activation
    */


    $(".personalizationButton").click(function() {
        if (!$(".personalization").hasClass('active')) {

            $(".personalization").slideDown();

            $(".personalization").addClass('active');
        }

    });

    $(".personalizeCancelButton").click(function() {

        $(".personalization").slideUp();
        $(".personalization").removeClass('active');
        /*$('body').css('background', originalBackgroundColor);*/
        return false;
    });

    /**
    * Personalization Background option select
    */

    handlePersonalizationBackOption();


    $(".backgroundOption").change(function() {
        handlePersonalizationBackOption();
    });




});

/**  
* Handle takeautoscreenshot option  
*/

EditItemAdminHandleTakeAutoScreenshotOption();

/**  
* Table save button toggle  
*/

UsersTableHandleInputSaveButton();

/**  
* Users table save button  
*/

UsersTableSaveInput();

/**  
* Blacklist show input for editing  
*/

BlacklistHandleEditButton();

/**  
* Blacklist show input for saving  
*/

BlacklistHandleSaveButton();

/**  
* Blacklist show input for deleting  
*/

BlacklistHandleDeleteButton();

/**  
* Black List Panel buttons handler  
*/

BlackListHandleAddItemButton();
BlackListHandleAddItemButton1();
BlackListHandleAddItemButton2();
BlackListHandleCancelPanelButton(); 
BlackListHandleCancelPanelButton1();
BlackListHandleCancelPanelButton2();

function showProgress() {

    $("#spinner").html("<img src='/images/ajax-loader-bar.gif' />");
    $("#spinner").attr("style", "display:inline");

}


/**
* Select the search engine
*/
var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);


if (sPage == "admin.aspx")
    searchEngineURL = "/diretorio/search_results.aspx?Query=";
else
    searchEngineURL = "/diretorio/search_results.aspx?q=";
// var searchEngineURL = "/diretorio/search_results.aspx?q=";
function changeSearchEngine(selected) {

    var searchEngine = $(selected).attr("class");


    $("#searchEngine").removeClass();
    $("#searchEngine").addClass(searchEngine);
    $("#searchEngineOptions").hide();
    $("#searchEngineOptions").removeClass();


    /**
    * Change the form search
    */
    switch (searchEngine) {
        case "diretorio":
            //			$("#aspnetForm").attr("action","/diretorio/search_results.aspx?q=");
            //			$("#aspnetForm").attr("target","");
            var sPath = window.location.pathname;
            var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);


            if (sPage == "admin.aspx")
                searchEngineURL = "/diretorio/search_results.aspx?Query=";
            else
                searchEngineURL = "/diretorio/search_results.aspx?q=";
            break;
        case "google":
            //			$("#aspnetForm").attr("action","http://google.pt?q=");
            //			$("#aspnetForm").attr("target",searchEngine);
            searchEngineURL = "http://google.pt/search?q=";
            break;
        case "intranet":
            //			$("#aspnetForm").attr("action","https://campus.tap.pt?k=");
            //			$("#aspnetForm").attr("target",searchEngine);
            searchEngineURL = "https://campus.tap.pt/Pages/Results.aspx?s=Campus%20TAP&k=";
            break;
        case "sapo":
            //			$("#aspnetForm").attr("action","http://pesquisa.sapo.pt/?q=");
            //			$("#aspnetForm").attr("target",searchEngine);	
            searchEngineURL = "http://pesquisa.sapo.pt/?q=";
            break;
        default:
            alert("nada");
    }
}


/**
* Change the list view 
*/
function itemListChanger(newClass) {

    //    if (window.location == "search_results.aspx")
    //        newClass = "list";
    $("#listButtons li.active").removeClass("active");

    $("a." + newClass).parent().addClass("active");

    //change the images 
    $("#itemList li").each(function() {
    $(this).attr("style", "background: url(style/img/" + newClass + "/" + $(this).attr("id") + ".image) center center  no-repeat;");
    });

    $("#itemList").removeClass();
    $("#itemList").addClass(newClass);

    $.cookie("listView", newClass);

    $("#listButtons li." + newClass).addClass("active");

    //remove the class from the parent div  
    $("#itemList").parent().removeClass();

    //add the new class to the parent  
    $("#itemList").parent().addClass("listHolder" + newClass);

    resetListPositions()


}


/**
* Update the item positions list 
*/
function updateListPositions(item) {

    var positionList = Array();

    $("#itemList li").each(function() {
        positionList[positionList.length] = $(this).attr("name");
    });
    //$(".listSerialized").val(positionList);
    //$(".listSerialized")[0].innerText = positionList;

    resetListPositions();
    //var str = $('#' + item.id).find("a.move").first().attr("href");

    //eval(str);

    var request = new XMLHttpRequest();
    var currentPageNr = $("#currentPage").attr("text");
    request.open("GET", "move.ajaxEvents?listIds=" + positionList + "&CurrentPage=" + currentPageNr, true);
    request.send(null);
    return false;

}

/**
* Delete an item from the list 
*/
function deleteListItem(item) {

    $("#dialog-confirm").dialog("close");

    eval(item[0].href);


}

/**
* Triger for removing tags, can be reused
*/

function activateRemoveTags() {
    $("a.bigTag span b").click(function() {
        $(this).parent().parent().hide('fast');
        $(this).parent().parent().remove();
        return false;
    });

};

/**
* IE support for nth-child
*/

function resetListPositions() {

    //if IE<9 returns false
    if (isIE) {

        // remove the class from all items
        $("#itemList.smallIcons li").removeClass("noMarginRight");

        // add the class to the items at the edges
        $("#itemList.smallIcons li:nth-child(6)").addClass("noMarginRight");
        $("#itemList.smallIcons li:nth-child(12)").addClass("noMarginRight");

    }
}

function handleTagEdit() {


    $(".tagBox").live('focus',function() {
        if ($(this).val() == "Adicionar tag")
            $(this).val("");
    });

    var newTag = "";
    /*
    $(".tagBox").live('change',function(){
    //create a new tag with the input value
					
    //alert($(this).val());
		
		if($(this).val()!=""){
    //copy the input value to the proto tag
    $(".proto a.bigTag span span").html($(this).val());
			
			newTag = $(".proto a.bigTag").clone();
    		
    //clean the prototype
    $(".proto a.bigTag span span").html();
    		
    $(this).parent().parent().before(newTag);
    		
    $(this).val("");
    		
    activateRemoveTags();	
    }
				
    //return false;
		
	});
    */
    // prevents form submit on enter key press in IE

    $(".tagBox").bind('keypress', function(e) {

        if (e.keyCode == 13) {
            if (isIE) $(this).blur();
            return false;
        }
    });


    $(".tagBox").blur(function() {

        if (!($(this).val() == "Adicionar tag")) {
            $(this).val("Adicionar tag");
        }

    });

    $(".tagBox").live('click',function() {
    $(this).val("");
    });


}

/**
* handles the Personalization Background Options inputs visibility 
*/

function handlePersonalizationBackOption() {
    $(".backgroundOptionP").hide();
    $(".personalization " + "." + $(".backgroundOption").val()).fadeIn('slow');
}


/**  
* When the users changes to value in the table input box shows the save button  
*/
function UsersTableHandleInputSaveButton() {

    $(".users td input").live("change",function() {
        $(this).parent().next().children().removeClass("disabled");
    });

}
/**  
* Saves the Maximum number of Items a user can have  
*/
function UsersTableSaveInput() {
    $(".users table * a.save").live("click",function() {

        //add spinning wheel for feedback  
        $(this).addClass("working");

        //get the user Id Number  
        var Id = $(this).parent().parent().attr('class');

        //get the value input 
        var Name = $(this).parent().parent().attr('class');
        //var Name = $(this).parent().prev().children().val();
        //save to database  



        //hide the button after value is saved  
        $(this).removeClass("working");
        $(this).addClass("disabled");

        //prevent page from jumping  
        return false;


    });


}

/**  
* Blacklist show input for editing  
*/

function BlacklistHandleEditButton() {
    $(".blacklist table * a.edit").live('click', function() {
        //hide the edit button  
        $(this).addClass("disabled");

        //hide the span with the value  
        $(this).parent().prev().children("span").hide();
        //show the input field  
        $(this).parent().prev().children("input").show();
        //show the save buttion  
        $(this).prev().removeClass("disabled");

        return false;

    });


}

/**  
* Blacklist show input for saving  
*/

function BlacklistHandleSaveButton() {
    $(".blacklist table * a.save").live('click', function() {

        //add spinning wheel for feedback  
        $(this).addClass("working");

        //get the row id  
        var blackListEntryId = $(this).parent().parent().attr('class');

        //get the value input  
        var blackListEntryValue = $(this).parent().prev().children("input").val();
        //save to database  

        //copy the input value to the span  
        $(this).parent().prev().children("span").html(blackListEntryValue);
        $(this).parent().prev().children("span").show();

        //hide the input  
        $(this).parent().prev().children("input").hide();

        //hide the button after value is saved  
        $(this).removeClass("working");
        $(this).addClass("disabled");

        //show edit button  
        $(this).next().removeClass("disabled");

        //hide save button  
        $(this).addClass("disabled");
        $(this).removeClass("working");



        return true;


    });
}

/**  
* Blacklist show input for deleting  
*/

function BlacklistHandleDeleteButton() {
    $(".blacklist table * a.delete").live('click', function() {

        //add spinning wheel for feedback  
        $(this).addClass("working");

        //delete from database  

        //remove the row  
        $(this).parent().parent().remove();


        return true;
    });


}


/**  
* Black List Item Add Button handler  
*/

function BlackListHandleAddItemButton() {


    $(".addBlackListItemButton").click(function () {

        //show the add black list item panel  
        $(".addBlackListItemButton").hide();
        $(".blackListAddPanel").show();

        return false;

    });

}

/**  
*/

function BlackListHandleCancelPanelButton() {


    $(".blackListAddPanel * a.cancel").click(function() {

        $(".blackListAddPanel").hide();
        $(".addBlackListItemButton").show();

        return false;

    });

}


/**  
* Black List Item Add Button handler  
*/

function BlackListHandleAddItemButton1() {


    $(".addBlackListItemButton1").click(function () {

        //show the add black list item panel  
        $(".addBlackListItemButton1").hide();
        $(".blackListAddPanel1").show();

        return false;

    });

}

/**  
*/

function BlackListHandleCancelPanelButton1() {


    $(".blackListAddPanel1 * a.cancel1").click(function () {

        $(".blackListAddPanel1").hide();
        $(".addBlackListItemButton1").show();

        return false;

    });

}

/**  
* Black List Item Add Button handler  
*/

function BlackListHandleAddItemButton2() {


    $(".addBlackListItemButton2").click(function () {

        //show the add black list item panel  
        $(".addBlackListItemButton2").hide();
        $(".blackListAddPanel2").show();

        return false;

    });

}

/**  
*/

function BlackListHandleCancelPanelButton2() {


    $(".blackListAddPanel2 * a.cancel2").click(function () {

        $(".blackListAddPanel2").hide();
        $(".addBlackListItemButton2").show();

        return false;

    });

}

/**  
* Handle takeautoscreenshot option  
*/

function EditItemAdminHandleTakeAutoScreenshotOption() {

    $(".takeautoscreenshot").live("change",function() {

        if ($(this).attr("checked") == true)
            $(".uploadScreenshotInput").attr("disabled", "disabled");
        else {
            $(".uploadScreenshotInput").attr("disabled", "");
        }

    });


}

/**  
* Clean Up Pesquisa Fields
*/

function clearFields() {
    $(".pesquisa").val('');

}


/**
* Handler to save selected color in personalize
*/

function savePerferedColor() {

    var selectedOption = $(".backgroundOption").val();
 
   if(selectedOption=="color")
   {
      
        var color = $('.backgroundColor').val();
        color = color.replace("#", "");
        var request = new XMLHttpRequest();
        request.open("GET", "personalize.ajaxEvents?Color=" + color, true);
        request.send(null);
        return false;
    }
}


function selectOption(selectObj) {

    if ($(selectObj).val() == "a partir do diretório")
        window.location="dir.aspx";


}


